package com.djb.TvSite.impl;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.djb.TvSite.api.VideoCommand;
import com.djb.TvSite.api.VideoFile;
import com.djb.TvSite.api.VideoFileRetrieval;

@Component
public class VideoFileRetrievalImpl implements VideoFileRetrieval {
	private static Process p;
	private static VideoFile currentVideo;
	public List<VideoFile> getVideoFiles(File dir) throws IOException{
		List<VideoFile> fileNames = new ArrayList<VideoFile>();
		for(File f : dir.listFiles()){
			if(f.isDirectory()){
				for(VideoFile videoFile: getVideoFiles(f)){
					fileNames.add(videoFile);
				}
			}
			else if(f.getName().toLowerCase().endsWith(".mp4")||f.getName().toLowerCase().endsWith(".mkv")||f.getName().toLowerCase().endsWith(".flv")||f.getName().toLowerCase().endsWith(".mpg")||f.getName().toLowerCase().endsWith(".avi")||f.getName().toLowerCase().endsWith(".wmv")){
				fileNames.add(new VideoFile(f.getCanonicalPath(),f.getName()));
				
			}
			
		}
		return fileNames;
	}
	
	public void playVideo(VideoFile video) throws IOException{
			String quit = "q";
			try {
				p.getOutputStream().write(quit.getBytes());
				p.getOutputStream().flush();
				p = Runtime.getRuntime().exec(new String[]{"omxplayer","-r","-ohdmi",video.getFilePath()});
				currentVideo = video;
			} 
			catch(Exception e){
				p = Runtime.getRuntime().exec(new String[]{"omxplayer","-r","-ohdmi",video.getFilePath()});
				currentVideo = video;
				
			}
		
	}
	public void deleteVideo(VideoFile video){
		File videoFile = new File(video.getFilePath());
		if(videoFile.exists()){
			videoFile.delete();
		}
	}
	
	public VideoFile getCurrentVideo(){
		
		return currentVideo;
	}
	
	
	public void sendCommand(VideoCommand command){
		try{
			p.getOutputStream().write(command.getCommand().getBytes());
			p.getOutputStream().flush();
		}
		catch(Exception e){
			System.out.println("no video is currently playing");
		}
		
		
	}
	

}
